using System.Collections;
using System.Collections.Generic;
using System.Text.RegularExpressions;
using UnityEngine;
using UnityEngine.Events;
using UnityEngine.UI;

public class UI组件_进度输入条 : UI基类
{
    public Image 背景;
    public InputField 输入框;
    public Slider 进度条;

    public bool 禁止拖至为零 = false;
   

    private UnityAction<float> 值被更改时;
    public bool 转255进制 = false;

    public void 初始化(float 值, UnityAction<float> 值被更改时 = null)
    {
        if (值被更改时 != null)
            this.值被更改时 = 值被更改时;
        同步进度(值);
    }

    public void 同步进度(float 值)
    {
        //刚刚初始化 = true;
        进度条.value = 值;
        if (转255进制)
            输入框.text = (值 * 255).ToString("0");
        else
            输入框.text = 值.ToString("0.00");

        上次输入的值 = 输入框.text;
        进度条发生改变 = 进度条.value;
    }

    void Start()
    {
        输入框.text = 进度条.value.ToString();
    }

    public void 输入框值改变时()
    {
        if (转255进制)
        {
            string ls = Regex.Match(输入框.text, @"[0-9]{0,3}").Value;
            输入框.text = ls;

            if (输入框.text != "")
            {
                int 值 = int.Parse(ls);
                值 = Mathf.Clamp(值, 0, 255);

                值被更改时(值 / 255f);
            }
        }
        else
        {
            string ls = Regex.Match(输入框.text, @"(\d+(\.\d+)?)").Value;

            string b = 输入框.text;
            if (b.Length >= 1 && b[b.Length - 1] == '.')
                输入框.text = ls + ".";
            else
                输入框.text = ls;
        }
    }

    public void 输入框结束编辑时()
    {
        if (转255进制)
        {
            int ls = 0;
            if (输入框.text != "")
                ls = int.Parse(输入框.text);

            ls = Mathf.Clamp(ls, 0, 255);

            进度条.value = ls / 255f;
        }
        else
        {
            验证输入是否合法();
            进度条.value = float.Parse(输入框.text);
        }
        值被更改时(进度条.value);
    }
    private string 上次输入的值 = "";
    private void 验证输入是否合法()
    {
        string str = 输入框.text;
        float value = -1;
        try
        {
            value = float.Parse(str);
        }
        catch
        {

        }
        if (value == -1)
        {
            输入框.text = 上次输入的值;
            return;
        }
        if (value > 1)
            输入框.text = "1";

        上次输入的值 = 输入框.text;
    }



    private float 进度条发生改变;
    private void Update()
    {
        if (禁止拖至为零)
            if (进度条.value <= 0)
                进度条.value = Mathf.Clamp(进度条.value, 0.01f, 1);

        if (进度条发生改变!= 进度条.value)
        {
            if (转255进制)
            {
                输入框.text = (进度条.value * 255).ToString("0");
            }
            else
                输入框.text = 进度条.value.ToString();

            
                值被更改时?.Invoke(进度条.value);
            进度条发生改变 = 进度条.value;
        }
    }
}
